package controller;

import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import pojo.Grade;
import pojo.Memberinfo;
import service.GradeService;
import service.MemberService;
import utils.FileNameUtil;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import utils.PageBean;


import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Date;

@Controller
@RequestMapping("/member")
public class MemberController {
    @Autowired
    private GradeService gradeService;
    @Autowired
    private MemberService memberService;
    @RequestMapping("/allMember")
    public String allMember(HttpServletRequest request,Model model){
        model.addAttribute("grade",gradeService.allGrade());
        request.setAttribute("ALL_USER_LIST",memberService.allMember());
        return "product";
    }
    @RequestMapping("/find")
    public String findMemberBySearch(String mname,int typeId,HttpServletRequest request,Model model){
        List<Memberinfo> list = memberService.findMemberBySearch(mname, typeId);
        request.setAttribute("ALL_USER_LIST",list);
        model.addAttribute("grade",gradeService.allGrade());
        return "product";
    }
    @RequestMapping("/allByPage")
    public String fenye(HttpServletRequest request, Model model){
        PageBean pageBean=new PageBean();
//        接受当前的页数
        Integer index=1;
        String ind=request.getParameter("index");
        if(ind!=null&&!"".equals(ind)){
            index=Integer.parseInt(ind);
        }
//        当前页数赋值给pagebean
        pageBean.setIndex(index);
//        总条数赋值给pageBean
        pageBean.setTotalCount(memberService.selectCount());
        List<Memberinfo> list = memberService.selectPage(pageBean.getStartRow(), pageBean.getSize());
        model.addAttribute("ALL_USER_LIST",list);
        model.addAttribute("pageBean",pageBean);
        model.addAttribute("grade",gradeService.allGrade());
        return "product";

    }


    @RequestMapping("findById")
    public String findById(int id,Model model){
        Memberinfo memberinfo = memberService.findById(id);
        model.addAttribute("memberinfo",memberinfo);
        model.addAttribute("grade",gradeService.allGrade());
        return "update";
    }


    @RequestMapping("update")
    public String update( Memberinfo memberinfo , HttpServletRequest request){
        memberinfo.setPhoto(saveFileName);
        System.out.println(memberinfo.toString());
        int num = -1;
        try {
            num =  memberService.update(memberinfo);
        } catch (Exception e) {
            e.printStackTrace();
        } if ( num >0 ){
            request.setAttribute("msg","增添成功");
        }else {
            request.setAttribute("msg","增添失败");
        }
        //清空saveFileName变量当中的内容
        saveFileName="";
        return "redirect:/member/allByPage";

    }





    //异步上传的图像名称
    String saveFileName ="";

    @RequestMapping("/getAll")
    public String getAll(HttpServletRequest request){
        List<Grade> list = gradeService.allGrade();
        request.setAttribute("list",list);
        return "product";

    }


    //异步Ajax上传图片请求
    @ResponseBody
    @RequestMapping("/ajaxImg")
    public Object ajaxImg(MultipartFile pimage , HttpServletRequest request){
        //提取生成文件名UUID+上传图片的后缀 .jpg .png
        saveFileName = FileNameUtil.getUUIDFileName() + FileNameUtil.getFileType(pimage.getOriginalFilename());
        //得到项目中的图片存储的路径
        String path = request.getServletContext().getRealPath("/image_big");
        //转存
        try {
            pimage.transferTo(new File(path+File.separator+saveFileName));
        } catch (IOException e) {
            e.printStackTrace();
        }

        //返回客户端JSON对象，封装图片的路径，为了在页面实现立即回显
        JSONObject object = new JSONObject();
        //放上出上传图片的名称
        object.put("imgurl",saveFileName);
        //如果 json对象返回必须返回toString,转换特点
        System.out.println(saveFileName);
        return object.toString();
    }

    @RequestMapping("/getGrade")
    public String getGrade(Model model){
        model.addAttribute("grade",gradeService.allGrade());
        return "addproduct";
    }


    @RequestMapping("/save")
    public String save(Memberinfo memberinfo ,HttpServletRequest request,Model model,int typeId){
        memberinfo.setPhoto(saveFileName);
        memberinfo.setCreatetime(new Date());
        System.out.println(memberinfo);
        model.addAttribute("grade",gradeService.allGrade());
        //info有表单提交的七个数据，ajax提交的图片数据，新产生的会员开通时间顺序
        int num = -1;
        try {
            num = memberService.save(memberinfo,typeId);
        } catch (Exception e) {
            e.printStackTrace();
        } if (num > 0 ){
            request.setAttribute("msg","增加成功");
        }else {
            request.setAttribute("msg","增加失败！");
        }
        //清空saveFileName变量当中的内容，为了让下次增加或者修改的异步ajax的上传处理
        saveFileName="";
        //增加成功后应该重新访问数据库，所以跳转到分页显示的action上
        return "forward:/member/allByPage" ;
    }


    @RequestMapping("/delete")
    public String deleteSingle(int id){
        memberService.deleteMwmber(id);
        return "redirect:/member/allByPage";

    }
    @RequestMapping("/deleteLot")
    public String deleteLot(String str){
        String[] split = str.split(",");
        Integer []ids=new Integer[split.length];
        for(int i=0;i<split.length;i++){
            ids[i]=Integer.parseInt(split[i]);
        }
        memberService.deltteAll(ids);
        return "redirect:/member/allByPage";

    }
}

